/* 
 * Created on 2008-1-29
 * Last modified on 2008-4-29
 * Powered by dev.yeqiangwei.com
 */
package com.yeqiangwei.commons.util;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.yeqiangwei.commons.util.ParamUtils;

/**
 * 
 * @author HongGuang
 */
public class FormUtils { 

	private static final Logger logger = Logger.getLogger(FormUtils.class);

	public static void formBuilder(HttpServletRequest request, Object bean) {
		Class<?> c = bean.getClass();
		Method[] ms = c.getMethods();
		for (int i = 0; i < ms.length; i++) {
			String name = ms[i].getName();
			if (name.startsWith("set")) {
				Class<?>[] cc = ms[i].getParameterTypes();
				if (cc.length == 1) {
					String type = cc[0].getName(); // parameter type
					try {
						// get property name:
						String prop = Character.toLowerCase(name.charAt(3)) + name.substring(4);
						// get parameter value:
						String param = null;
						if (type.equals("java.lang.String")) {
							param = ParamUtils.getStringParameter(request, prop, "");
							ms[i].invoke(bean, new Object[] { param });
						} else if (type.equals("int") || type.equals("java.lang.Integer")) {
							param = ParamUtils.getStringParameter(request, prop, "0");
							ms[i].invoke(bean, new Object[] { new Integer(param) });
						} else if (type.equals("long") || type.equals("java.lang.Long")) {
							param = ParamUtils.getStringParameter(request, prop, "0");
							ms[i].invoke(bean, new Object[] { new Long(param) });
						} else if (type.equals("boolean") || type.equals("java.lang.Boolean")) {
							param = ParamUtils.getStringParameter(request, prop, "false");
							ms[i].invoke(bean, new Object[] { Boolean.valueOf(param) });
						} else if (type.equals("short") || type.equals("java.lang.Short")) {
							param = ParamUtils.getStringParameter(request, prop, "0");
							ms[i].invoke(bean, new Object[] { Short.valueOf(param) });
						} else if (type.equals("byte") || type.equals("java.lang.Byte")) {
							param = ParamUtils.getStringParameter(request, prop, "0");
							ms[i].invoke(bean, new Object[] { Byte.valueOf(param) });
						} else if (type.equals("double") || type.equals("java.lang.Double")) {
							param = ParamUtils.getStringParameter(request, prop, "0");
							ms[i].invoke(bean, new Object[] { Double.valueOf(param) });
						}
					} catch (Exception e) {
						logger.error(e.toString());
					}
				}
			}
		}
	}
}
